package com.fowo.api.common.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

/**
 * 提供支持长整数安全序列化处理
 * @author yl_ls
 */
public class LongSerializer extends JsonSerializer<Object> {
    private static final Long MAX_SAFE_INTEGER = 9007199254740991L;
    private static final Long MIN_SAFE_INTEGER = -9007199254740991L;

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        Long v = (Long) value;
        if (v > MAX_SAFE_INTEGER || v < MIN_SAFE_INTEGER) {
            gen.writeString(v.toString());
            return;
        }
        gen.writeNumber(v);
    }
}
